// app.js
App({
  onShow() {
    this.checkLoginStatus()
  },
  checkLoginStatus () {
    let loginFlag = false
    if (loginFlag) {
      console.log('has loginFlag');
      wx.checkSession({
        success: () => {
          console.log('checkSession success');
          let userInfo = wx.getStorageSync('userInfo')
          if (userInfo) {
            this.globalData.userInfo = JSON.parse(userInfo)
          }
        },
        fail: () => {
          console.log('checkSession fail');
          this.doLogin()
        }
      })
    } else {
      console.log('no loginFlag');
      this.doLogin()
    }
  },
  doLogin () {
    wx.login({
      success: loginRes => {
        console.log('wx.login success', loginRes);
        if (loginRes.code) {
          wx.request({
            url: 'https://bm.zhushui.net/tax/api/auth/session/openid',
            method: 'POST',
            header: {},
            data: {
              code: loginRes.code
            },
            success: res => {
              res = res.data
              if (res.status === true) {
                const data = {
                  token: res.entity.token,
                  openId: res.entity.openId
                }
                this.globalData.userInfo = {...data}
                const pages = getCurrentPages()
                if (pages.length && pages[0].hasOwnProperty('getToken')) {
                  pages[0].getToken({ token: data.token, openId: data.openId })
                }
                wx.setStorageSync('loginFlag', true)
                wx.setStorageSync('userInfo', JSON.stringify(data))
              }
            },
            fail: err => {
              wx.setStorageSync('loginFlag', false)
            }
          })
        }
      },
      fail: err => {
        console.log('wx.login fail');
      }
    })
  },
  globalData: {
    userInfo: null,
    host: 'https://bm.zhushui.net/tax'
  }
})
